package com.example.shkjdemo.bluetooth

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothHeadset
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.orhanobut.logger.Logger
import java.lang.reflect.Method


class MyBleBroadcastReceiver : BroadcastReceiver() {
    private val TAG = "MyBleBroadcastReceiver"
    lateinit var observerBluetooth: ObserverBluetooth
    override fun onReceive(context: Context?, intent: Intent?) {
        when (intent?.action) {

            BluetoothDevice.ACTION_FOUND -> {
                // 从 Intent 中获取发现的 BluetoothDevice
                val device =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice
                if (!device.name.isNullOrEmpty()) {
                    Logger.d("$TAG ${device.name + device.address}")
                }
                observerBluetooth.addDevice(device)
            }
            BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                val bondState = intent.getIntExtra(
                    BluetoothDevice.EXTRA_BOND_STATE,
                    BluetoothDevice.BOND_NONE
                )
                val device =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice

                when (bondState) {
                    BluetoothDevice.BOND_BONDED -> {
                        //配对成功
                        Log.i(TAG, "配对成功 Device:" + device.name + " bonded.");
//                      //连接蓝牙设备
                        val batteryMethod: Method =
                            BluetoothDevice::class.java.getDeclaredMethod(
                                "getBatteryLevel",
                               null
                            )
                        batteryMethod.isAccessible = true

                        val level = batteryMethod.invoke(
                            device,
                            null as Array<Any?>?
                        ) as Int

                        val deviceName = device.name;
                        Logger.d("$deviceName    电量:  $level")
                    }

                    BluetoothDevice.BOND_BONDING -> {
                        Log.i(TAG, "正在配对 Device:" + device.name + " bonding.")

                    }

                    BluetoothDevice.BOND_NONE -> {
                        Log.i(TAG, "配对失败，在这里做重新配对: Device:" + device.name + " not bonded.");

                    }
                }
            }

            BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT -> {
                val command =
                    intent.getStringExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD)
                Logger.e("$TAG,command = $command")
                when (command) {
                    "+IPHONEACCEV" -> {
                        val args =
                            intent.getSerializableExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_ARGS) as Array<*>

                        if (args.size >= 3 && args[0] is Int && ((args[0]) as Int) * 2 + 1 <= args.size) {
                            for (i in 0..((args[0]) as Int)) {
                                if (args[i * 2 + 1] !is Int || args[i * 2 + 2] !is Int) {
                                    continue
                                }
                                if (args[i * 2 + 1] == 1) {
                                    val level = ((args[i * 2 + 2]) as Int + 1) / 10.0f
                                    Log.i(TAG, "获取蓝牙设备电量: battery   $level")
                                    break;
                                }
                            }
                        }
                    }

                }

            }

        }
    }

    /**
     * 观察蓝牙扫描新设备
     * */
    interface ObserverBluetooth {
        /**
         * 发现蓝牙设备
         * */
        fun addDevice(device: BluetoothDevice)

        /**
         * 连接蓝牙
         * */
        fun connect(device: BluetoothDevice)
    }

    fun registerObserver(observerBluetooth: ObserverBluetooth) {
        this.observerBluetooth = observerBluetooth
    }

}